package com.hardy.Thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Author: fuxh3@lenovo.com
 * Date: Created in 2018/2/24 0024
 */
public class CountdownLatchTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final CountDownLatch cdOrder = new CountDownLatch(1);
        final CountDownLatch cdAnswer = new CountDownLatch(3);
        for(int i=0;i<3;i++){
            Runnable runnable = new Runnable(){
                public void run(){
                    try {
                        System.out.println("thread" + Thread.currentThread().getName() +
                                                        " zhun bei jie shou order");
                        cdOrder.await();
                        System.out.println("thread" + Thread.currentThread().getName() +
                                                        " yi jie shou ming lin");
                        Thread.sleep((long)(Math.random()*10000));
                        System.out.println("thread" + Thread.currentThread().getName() +
                                                        " hui yin ming lin chu li jie guo");
                        cdAnswer.countDown();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);
        }
        try {
            Thread.sleep((long)(Math.random()*10000));

            System.out.println("thread" + Thread.currentThread().getName() +
                                            "ji jiang fa bu ming ling");
            cdOrder.countDown();
            System.out.println("thread" + Thread.currentThread().getName() +
                                            "yi fa song ming ling, zheng zhun bei jie guo");
            cdAnswer.await();
            System.out.println("thread" + Thread.currentThread().getName() +
                                            "yi shou dao suo you xiang ying jie guo");
        } catch (Exception e) {
            e.printStackTrace();
        }
        service.shutdown();
    }
}
